<template>
	<!-- 系统目录 中药目录 -->
	<div class="LocationCatalog">
		<!-- main -->
		<div class="main">
			<!-- right -->
			<div class="main-right">
				<!-- tit -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #00aaff;color: #fff;"></i>
						<span style="font-size: 16px;font-weight:300;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-b">
						<span style="font-size: 12px;color: #606266;font-weight: bold;">库房名称：</span>
						<el-dropdown @command="handleCommand" trigger="click">
							<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
							<el-dropdown-menu slot="dropdown">
							  <el-dropdown-item command="a">中药库</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">盘点日期：</span>
						<el-date-picker v-model="pdDate" type="daterange" align="right" size="mini" unlink-panels 
						range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
						</el-date-picker>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- table -->
				<div class="table">
					<el-table 
					  :data="tableData" 
					  border 
					  @cell-dblclick="handleCellDblClick"
					  element-loading-text="数据加载中..." 
					  v-loading="loading" 
					  element-loading-spinner="el-icon-refresh"
					  highlight-current-row 
					  @current-change="handleCurrentTableChange">
					  
					  <!-- 其他列保持不变 -->
					  
					  <!-- 账面包装单位数量列 -->
					  <el-table-column prop="pacQuantity" label="账面包装单位数量" width="120"></el-table-column>
					  
					  <!-- 实存包装单位数量列 - 可编辑 -->
					  <el-table-column prop="actualPacQuantuty" label="实存包装单位数量" width="120">
					    <template slot-scope="scope">
					      <el-input
					        v-if="editingRow === scope.row && editingField === 'actualPacQuantuty'"
					        v-model.number="scope.row.actualPacQuantuty"
					        @input="handleInputChange($event, scope.row)"
					        @blur="handleBlur(scope.row)"
					        size="mini"
					        class="cell-edit-input"
					        type="number"
					        :min="0"
					        :step="1"
					      ></el-input>
					      <span v-else>{{ scope.row.actualPacQuantuty }}</span>
					    </template>
					  </el-table-column>
					  
					  <!-- 盈亏包装单位数量列 -->
					  <el-table-column prop="plActualPacQuantuty" label="盈亏包装单位数量" width="120"></el-table-column>
					  
					  <!-- 包装单位成本单价列 -->
					  <el-table-column prop="pacUntCosAmt" label="包装单位成本单价" width="120"></el-table-column>
					  
					  <!-- 实存成本金额列 -->
					  <el-table-column prop="actualCostAmt" label="实存成本金额" width="120"></el-table-column>
					  
					  <!-- 盈亏成本金额列 -->
					  <el-table-column prop="plCostAmt" label="盈亏成本金额" width="150"></el-table-column>
						<!-- <el-table-column label="系统序号" prop="id" width="88"></el-table-column> -->
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- edit -->
			<!-- 			<el-table-column fixed="right" label="操作" width="88">
						  <template slot-scope="scope">
							  <div class="editbox" style="text-align: center;">
								<el-button type="text" @click="editFormValue(scope.row)" size="mini">编辑</el-button>
								<el-button type="text" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
							  </div>
						  </template>
						</el-table-column> -->
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
					</el-table>
					<!-- <span v-if="noData"> {{ noData }} </span> -->
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20,50,100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background
					>
					</el-pagination>
					<div class="feetBtn">
						<!-- btn3 -->
						<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="small" plain
							@click="feetHandClick(v,i)" style="margin-left: 12px;">{{ v.title }}
						</el-button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- add dialog -->
		<div class="addDiglog">
			<addCountDiglog ref='sonRef' @untable-data="handleUntableData" :parent-method="loadData"></addCountDiglog>
		</div>
		<!-- 打印设置对话框 -->
<!-- 		<print-settings-dialog 
		  :visible.sync="printDialogVisible" 
		  :content="printContent"
		/> -->
			
	</div>
</template>

<script>
	// selfs / js
	// import LocationCatalog from '@/external/LocationCatalog.js'
	//  selfs / props
	import addCountDiglog from './addCount.vue'
	import PrintSettingsDialog from '@/components/PrintSettingsDialog.vue';
	// 接口
	// import { getTcmSkVo,PdtcmSk } from "@/api/systemCatalogue/Western.js";
	import { getTcmSkVo,PdtcmSk } from "@/api/systemCatalogue/traMedici.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addCountDiglog,PrintSettingsDialog
		},
		data() {
			return {
				// 新增数据
				editingCell: null, // 当前编辑的单元格
				editingRow: null,   // 当前编辑的行
				editingField: '',   // 当前编辑的字段
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				id:'',
				activeName:'first',
				pdDate:'', // 盘点日期
				windowWidth: '', //表格自适应宽度
				CatalogueName:'库存盘点明细',
				DropDownedName:'中药库',
				iconComes:'el-icon-yllb',
				// boolean
				loading:false,
				disabled:true,
				printDialogVisible: false,
				// showChild:false, // 控制子组件挂载
				// number
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				res:[],
				// title右侧按钮
				headerBtn:[
					{ title:"刷新", type:"", icon:"el-icon-refresh", loading:false}, { title:"高级", type:"primary", icon:"", loading:false},
				],
				feetBtn:[
				 // { refesh:"refesh", title:"新增", type:"primary", icon:"el-icon-plus" },
				 // { refesh:"refesh", title:"删除", type:"primary", icon:"el-icon-s-claim" },
				 // { refesh:"refesh", title:"草稿录入", type:"primary", icon:"el-icon-document-checked" },
				 // { refesh:"refesh", title:"合并提交", type:"primary", icon:"el-icon-sort" },
				 // { refesh:"refesh", title:"审核", type:"primary", icon:"el-icon-printer" },
				 // { refesh:"refesh", title:"结转", type:"primary", icon:"el-icon-upload2" },
				 { refesh:"refesh", title:"清空实存", type:"primary", icon:"el-icon-printer" },
				 { refesh:"refesh", title:"打印", type:"primary", icon:"el-icon-upload2" },
				 { refesh:"refesh", title:"关闭", type:"primary", icon:"el-icon-close" },
				 ],
				// tableRows
				tableRows:[
					{ name:"药品编码", prop:"drugCode"},{ name:"药品序号I", prop:"drugId"},
					{ name:"药品名称", prop:"drugName"},{ name:"规格描述", prop:"drugSpec"},
					{ name:"药品剂型", prop:"drugform" },{ name:"生产厂家", prop:"prodentpName"},
					{ name:"生产批号", prop:"manuLotnum"},{ name:"账面包装单位数量", prop:"pacQuantity"},
					{ name:"包装单位", prop:"pacUnt"},{ name:"账面最小单位数量", prop:"minQuantity"},
					{ name:"最小单位", prop:"minUnt"},{ name:"实存包装单位数量", prop:"actualPacQuantuty"},
					
					{ name:"实存最小单位数量", prop:"drugCode"},{ name:"盈亏包装单位数量", prop:"plActualPacQuantuty"},
					{ name:"盈亏最小单位数量", prop:"plActualMinQuantuty"},{ name:"盈亏成本金额", prop:"plCostAmt"},
					{ name:"盈亏零售金额", prop:"plRetailAmt" },{ name:"包装单位成本单价", prop:"pacUntCosAmt"},
					{ name:"包装单位零售单价", prop:"pacUntRetailAmt"},{ name:"最小单位成本单价", prop:"minCosAmt"},
					{ name:"最小单位零售单价", prop:"minRetailAmt"},{ name:"账面成本金额", prop:"bookCostAmt"},
					{ name:"账面零售金额", prop:"bookRetailAmt"},
					{ name:"实存零售金额", prop:"actualRetailAmt"},{ name:"录入人", prop:"inputId"},
					{ name:"录入时间", prop:"inputTime"},{ name:"包装数量", prop:"pacQuantity"},
					{ name:"货位序号", prop:""},
				],
				// tableRows
				untableRows:[
					{ name:"数据表", prop:"docType" },{ name:"状态", prop:"state" },
					{ name:"单据编号", prop:"docNum" },{ name:"库房名称", prop:"shedId" },
					{ name:"盘点日期", prop:"" },{ name:"制单人", prop:"createId" },
					{ name:"制单时间", prop:"createTime" },{ name:"审核人", prop:"pacCnt" },
					{ name:"审核时间", prop:"pacUnt" },{ name:"隶属机构", prop:"pacCnt" },
					{ name:"备注", prop:"remake" }
				],
				addForm:{
					"actualCostAmt": 0,
					"actualMinQuantuty": 0,
					"actualPacQuantuty": 0,
					"actualRetailAmt": 0,
					"bookCostAmt": 0,
					"bookRetailAmt": 0,
					"drugCode": "",
					"drugId": 0,
					"drugName": "",
					"drugSpec": "",
					"id": 0,
					"inputId": 0,
					"inputTime": "",
					"invId": 0,
					"manuLotnum": "",
					"minCosAmt": 0,
					"minQuantity": 0,
					"minRetailAmt": 0,
					"minUnt": "",
					"pacCnt": 0,
					"pacQuantity": 0,
					"pacUnt": "",
					"pacUntCosAmt": 0,
					"pacUntRetailAmt": 0,
					"plActualMinQuantuty": 0,
					"plActualPacQuantuty": 0,
					"plCostAmt": 0,
					"plRetailAmt": 0,
					"prodentpName": "",
					"prodentpNameId": 0,
					"skId": 0
				},
				tableData: [],
				untableData:[],
				pickerOptions: {
				  shortcuts: [{
					text: '最近一周',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
					  picker.$emit('pick', [start, end]);
					}
				  }, {
					text: '最近一个月',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
					  picker.$emit('pick', [start, end]);
					}
				  }, {
					text: '最近三个月',
					onClick(picker) {
					  const end = new Date();
					  const start = new Date();
					  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
					  picker.$emit('pick', [start, end]);
					}
				  }]
				},
			};
		},
		computed: {
		   
		},
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			});
		},
		methods: {
			/*
				数据源
			*/
			async loadData(){
				this.id = this.$route.query.id
				let res = await getTcmSkVo({ id:this.id});
				if(res.code === 200){
					// console.log(res.data.content);
					this.tableData = res.data
					this.totalSize = res.data.totalSize
				}else{
					this.$message({ type: 'error', message: res.message });
					this.tableData = [];
				}
			},
			handleClick(tab, event) {
				console.log(tab, event);
			},
			// 处理不可盘点数据
			handleUntableData(res) {
				console.log(res,'jieksasdoada');
				if(res.code === 200){
					this.activeName = 'first';
					this.tableData.push(res.data);  // 将数据赋值给tableData
				}else if(res.code === 201){
					this.activeName = 'second';
					this.untableData = res.data;  // 将数据赋值给untableData
				}
			},
			// 处理单元格双击事件
			handleCellDblClick(row, column, cell, event) {
			  // 只处理"实存包装数量"列
			  if (column.property === 'actualPacQuantuty') {
			    this.editingRow = row;
			    this.editingField = 'actualPacQuantuty';
			    this.$nextTick(() => {
			      const input = cell.querySelector('.cell-edit-input input');
			      if (input) {
			        input.focus();
			        // 选中文本以便直接输入
			        input.select();
			      }
			    });
			  }
			},
			
			// 处理输入变化
			handleInputChange(value, row) {
			  // 确保输入的是有效数字
			  const numValue = Number(value);
			  if (isNaN(numValue)) {
			    // 如果输入无效，恢复之前的值
			    this.$nextTick(() => {
			      row.actualPacQuantuty = row._originalValue || 0;
			    });
			    return;
			  }
			  
			  // 保存原始值以便恢复
			  if (!row._originalValue) {
			    row._originalValue = row.actualPacQuantuty;
			  }
			  
			  // 更新实存包装数量
			  row.actualPacQuantuty = numValue;
			  
			  // 计算盈亏包装单位数量
			  row.plActualPacQuantuty = row.actualPacQuantuty - row.pacQuantity;
			  
			  // 计算实存成本金额
			  row.actualCostAmt = row.actualPacQuantuty * row.pacUntCosAmt;
			  
			  // 计算盈亏成本金额
			  row.plCostAmt = row.plActualPacQuantuty * row.pacUntCosAmt;
			  
			  // 计算实存零售金额
			  if (row.pacUntRetailAmt) {
			    row.actualRetailAmt = row.actualPacQuantuty * row.pacUntRetailAmt;
			  }
			  // 计算盈亏零售金额
			  if (row.pacUntRetailAmt) {
			    row.plRetailAmt = row.plActualPacQuantuty * row.pacUntRetailAmt;
			  }
			  // 计算盈亏最小单位数量
			  // if (row.pacUntRetailAmt) {
			  //   row.plRetailAmt = row.plActualPacQuantuty * row.pacUntRetailAmt;
			  // }
			  
			},
			
			// 处理输入框失焦事件
			async handleBlur(row) {
			  try {
			    // 确保值是数字
			    if (typeof row.actualPacQuantuty !== 'number') {
			      row.actualPacQuantuty = Number(row.actualPacQuantuty) || 0;
			    }
			    
			    // 合并当前行数据到addForm
			    this.addForm = {
			      ...this.addForm,  // 保留原有addForm中的数据
			      ...row            // 添加当前行的所有数据
			    };
			    
			    // 打印合并后的addForm
			    console.log('合并后的addForm:', this.addForm);
			    
			    // 调用保存接口
			    const result = await PdtcmSk(this.addForm);
			    
			    if (result.code === 200) {
			      this.$message.success(result.message);
			    } else {
			      this.$message.error(result.message);
			    }
			  } catch (error) {
			    console.error('保存出错:', error);
			    this.$message.error('保存失败');
			  } finally {
			    // 重置编辑状态
			    this.editingRow = null;
			    this.editingField = '';
			    // 清除原始值备份
			    if (row._originalValue) {
			      delete row._originalValue;
			    }
			  }
			},
			// 模拟保存接口
			async savePd(data) {
			    console.log('保存数据:', data);
			    // 这里应该是实际的API调用
			    return { code: 200, message: '保存成功' };
			},
			// props
			feetHandClick(v,i){
				console.log(v,i,'ppppppppppppppp');
				// i event
				// 处理逻辑 => 关闭
				if(v.title === '关闭' || v.title.includes('关闭')){
					setTimeout(() =>{
						window.history.back();
					},888)
				}
				switch (i) {
					case 0:
						// 新增
						this.nameTitle = '新增';
						this.$refs.sonRef.open(this.nameTitle)
					break;
					case 1:
						// 处理索引0的逻辑 => 删除
						if(this.currentTable.length === 0){
							this.$message({ type: 'warning', message: '请先单击选择一条数据'});
						}else if(this.currentTable.state != 0){
							this.$message({ type: 'error', message: '只能删除草稿数据！'});
						}else{
							this.$confirm("是否删除?", "提示", {
							  confirmButtonText: "确定",
							  cancelButtonText: "取消",
							  type: "warning",
							})
							.then(async() => {
								// 状态 => 删除
							}).catch(() => {
								this.$message({ type: "info",message: '已取消'});
							});
						}
					break;
					case 2:
					// 提交
					
					break;
					case 3:
					// 审核
					
					break;
					case 4:
					// 过单
					
					break;
					case 7:
					// 打印
					 this.printDialogVisible = true;
					break;
					
				}
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteTP({
						id: rowId
					})
					if(res.code === 200){
						this.$message({type:'success',message:'已删除'});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			
			// 编辑保存
			saveEditData(){
				
			},
			
			/*
				选择框
			*/

			/*
				about input
			*/

			/*
				about table
			*/
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 20; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 12; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 0;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 12px
		             else if ("A" <= char && char <= "Z") length += 12;
		             // 中文字符 16px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
		             // 其他 8px
		             else length += 8;
		           }
		           return length;
		         }
		    },
			// 新增等步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:// 处理索引1的逻辑 页面刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
					break;
					case 1:
						// 处理索引2的逻辑
						this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
					break;
				}
			},
			// 表格单选
			handleCurrentTableChange(val){
				console.log(val);
				this.currentTable = val
			},
			// db events 双击表格行
			handledbRow(row, column, event){
				// if(row){
				// 	this.loading = true;
				// 	setTimeout(()=>{
				// 		console.log(row,'双击过后查看');
				// 		// 使用点语法
				// 		// res.data.watch = true;
				// 		let param = {
				// 			id:row.id,
				// 			label:'查看',
				// 			isShow:false,
				// 			system:true,
				// 		}
				// 		this.loading = false;
				// 		this.$refs.addModel.openAddModel(param);
				// 	},888)
				// } else { 
				// 	this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				// }
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  // 这里的 command 就是你点击的菜单项的 command 属性值
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '中药库'
				  break;
				// ... 其他 case
			  }
			},
			// 拦截

			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 188;
			},
		}
	}
</script>

<style lang="less" scoped>
	.LocationCatalog {
		height: 100%;
		width: 100%;
		// table
		/deep/ .el-button{
			background-color: var(--primary-color, #409EFF) !important;
			color: var(--text-color, #304156) !important;
		}
		/deep/ .el-table .cell{
			font-size: 12px;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		/deep/ .el-table th{
			background-color: #f1f1f1;
			border: none;
			color: #2d2d2d;
		}
		// header
		.header {
			display: flex;
			flex-direction: row;
			align-items: center;
			height: 40px;
			background-color: #efefef;
			padding: 4px;

			// justify-content: space-evenly;
			// icon
			.header-icon {
				display: flex;
				align-items: center;
				justify-content: start;
				.header-btn{
					margin-left: 20px;
				}
			}

		}

		// main
		.main {
			width: 100%;
			display: flex;
			justify-content: left;
			padding: 4px;
			// right
			.main-right {
				width: 100%;
				height: 100%;
				// icon
				.main-icon {
					display: flex;
					align-items: center;
					line-height: 40px;
					.main-icon-a{
						// width: 240px;
						// background-color: #00557f;
					}
					.main-icon-b{
						margin-left: 28px;
						/deep/ .el-dropdown{
							font-size: 12px;
							cursor: pointer;
						}
						/deep/ .el-dropdown:hover {
							font-weight: bold;
							color: #66b1ff;
						}
						/deep/ .el-icon--right{
							// background-color: #66b1ff;
						}
						/deep/ .el-popper[x-placement^=bottom]{
							margin-top: 0;
						}
					}
					// c
					.main-icon-c{
						margin-left: 28px;
						display: flex;
						align-items: center;
					}
				}
				
				// table
				.table{
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #00557f !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
					/deep/ .el-table{
						width: 100%;
					}
					/deep/ .el-table .cell{
						font-size: 12px;
						text-align: left;
					}
				}
			}
		}
		.feet{
			height: 100px;
			width: 100%;
			padding: 12px;
			position: fixed;
			// top: 0;
			bottom: 10px;
			left: 168px;
			right: 0;
			.feetBtn{
				display: flex;
				justify-content: start;
				align-items: center;
				flex-wrap: wrap;
				gap: 8px;
			}
		}
	}
</style>